package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.VoiceDisLike;
import com.tanhua.domain.mongo.VoiceLike;
import com.tanhua.domain.mongo.VoicePublish;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class VoicePublishApiImpl implements VoicePublishApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存语音到语音发布表
     *
     * @param userId
     * @param soundUrl
     * @return 语音记录的主键id
     */
    @Override
    public ObjectId saveVoice(Integer userId, String soundUrl) {
        //查询出语音条数,每次+1
        Query query = new Query();
        long count = mongoTemplate.count(query, VoicePublish.class);
        count++;

        VoicePublish voicePublish = new VoicePublish();
        Date date = new Date();
        voicePublish.setCreated(date.getTime());
        voicePublish.setId(ObjectId.get());
        voicePublish.setNum((int) count);
        voicePublish.setUrl(soundUrl);
        voicePublish.setUserId(userId);

        //保存
        mongoTemplate.save(voicePublish);
        //返回主键id
        return voicePublish.getId();
    }


    @Override
    public VoicePublish queryVoice(Long currentUserId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").ne(currentUserId));
        //计算总共记录数
        long queryPage = mongoTemplate.count(query, VoicePublish.class);

        if (queryPage <= 1) queryPage = 2;

        //随机查询一条记录，然后判断是否可用，如果有效则返回
        VoicePublish voicePublish = null;
        while (true) {
            //随机生成单条记录
            long num = RandomUtils.nextLong(1, queryPage + 1);
            query.limit(1).skip(num - 1);
            List<VoicePublish> voicePublishes = mongoTemplate.find(query, VoicePublish.class);
            //如果没有则退出循环
            if (CollectionUtils.isEmpty(voicePublishes)) break;
            voicePublish = voicePublishes.get(0);
            //判断是否为喜欢或不喜欢表中条件
            Query queryConfirm = new Query();
            //判断是否存在喜欢与不喜欢，如果均没有则返回
            queryConfirm.addCriteria(Criteria.where("userId").is(currentUserId.intValue())
                    .and("likeNum").is(voicePublish.getNum()));
            //如果都没有，则退出循环生成
            if (!mongoTemplate.exists(queryConfirm, VoiceLike.class)
                    && !mongoTemplate.exists(queryConfirm, VoiceDisLike.class)) break;
        }

        return voicePublish;
    }
}
